import json
import time
import pymongo
import requests


class MongoListener:
    def __init__(self, mongo_ip, mongo_port):
        self.mongo_ip = mongo_ip
        self.client = pymongo.MongoClient(host=mongo_ip, port=int(mongo_port))
        self.run11 = self.client.guidang4.RUN11
        # self.run1 = self.client.guidang4.RUN1
        self.config = self.client.guidang4config.config
        self.id_pools = self.client.guidang4.id_pools

    def insert_stranger_request(self, ip, port, face_id, camera_id, timestamp, uri, base64, feature=None):
        quest_uri = "http://{}:{}/insert_stranger".format(ip, port)
        payload = {
            "id": face_id,
            "camera_id": camera_id,
            "timestamp": timestamp,
            "uri": uri,
            "base64": base64
        }
        if feature:
            payload.update({"feature": feature})

        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        return requests.request("POST", quest_uri, headers=headers, data=json.dumps(payload))

    # def find_run1(self, hezi_guidang_ip):
    #     results = self.run1.find()
    #     port_list = []
    #     for result in results:
    #         if result["hezi_guidang_ip"] != hezi_guidang_ip:
    #             port_list.append(result["_id"])
    #
    #     return port_list

    def find_config(self, hezi_guidang_ip):
        all_img = self.config.find({"repo": "D"})
        box_ip_list = []
        box_img = {}
        for img in all_img:
            if img["h_ip"] == hezi_guidang_ip:
                continue

            if img["h_ip"] not in img:
                box_ip_list.append(img["h_ip"])
                box_img[img["h_ip"]] = img

        return box_ip_list, box_img

    def mongo_listen(self, sleep_time):
        # 按时间戳
        results = self.run11.find()
        for result in results:
            print("RUN11ing...%s" % time.time())
            # 将RUN3 修改为全部数据插入 ip, port, face_id, camera_id, timestamp, uri, base64=None, feature=feature
            face_id = result.get("_id")
            feature = result.get("ovn_f")
            camera_id = result.get("camera_id")
            timestamp = result.get("timestamp")
            uri = result.get("uri")
            hezi_guidang_ip = result.get("hezi_guidang_ip")

            # port_list = self.find_run1(hezi_guidang_ip)
            port_list, port_img = self.find_config(hezi_guidang_ip)

            if port_list:
                for port in port_list:
                    # ip = self.mongo_ip
                    result = self.insert_stranger_request(port_img.get(port).get("ip"), port, face_id, camera_id, timestamp, uri, base64='',
                                                          feature=feature)
                    msge = result.json()
                    print(msge)

            self.clear_handled(face_id)

        time.sleep(sleep_time)

    def clear_handled(self, face_id):
        self.run11.delete_one({"_id": str(face_id)})


def loops(mongo_ip, mongo_port, sleep_time):
    while True:
        try:
            ml = MongoListener(mongo_ip, mongo_port)
            while True:
                ml.mongo_listen(sleep_time)
        except Exception as e:
            print(e)
            time.sleep(5)


if __name__ == '__main__':
    with open('../config.py', 'r') as conf_r:
        exec(conf_r.read())

    mongo_host = mongoinfo['ip']
    mongo_port = mongoinfo['port']

    loops(mongo_host, mongo_port, 10)
